﻿using System;
using System.Collections.Generic;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Structure;
using Autodesk.Revit.UI;

namespace YJKRevitColumn.ColumnModule
{
	public class ColumnSplitWallControler
	{
		public ColumnSplitWallControler(UIApplication uiApplication)
		{
			this.m_uiApplication = uiApplication;
			this.m_Doc = this.m_uiApplication.ActiveUIDocument.Document;
		}

		public void ColumnJoinWall(Element column, StructuralType sType)
		{
			foreach (Element wall in this.GetWallsIntersectElement(column))
			{
				this.JoinTwoElements(column, wall, sType);
			}
		}

		private List<Element> GetWallsIntersectElement(Element column)
		{
			List<Element> list = new List<Element>();
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(this.m_Doc);
			filteredElementCollector.OfClass(typeof(Wall));
			ElementIntersectsElementFilter elementIntersectsElementFilter = new ElementIntersectsElementFilter(column);
			filteredElementCollector.WherePasses(elementIntersectsElementFilter);
			foreach (Element item in filteredElementCollector)
			{
				list.Add(item);
			}
			return list;
		}

		private void JoinTwoElements(Element column, Element wall, StructuralType sType)
		{
			if (!JoinGeometryUtils.AreElementsJoined(this.m_Doc, column, wall))
			{
				JoinGeometryUtils.JoinGeometry(this.m_Doc, column, wall);
				this.m_Doc.Regenerate();
			}
			this.SetJoinOrder(column, wall, sType);
		}

		private void SetJoinOrder(Element column, Element wall, StructuralType sType)
		{
			if (JoinGeometryUtils.IsCuttingElementInJoin(this.m_Doc, wall, column))
			{
				JoinGeometryUtils.SwitchJoinOrder(this.m_Doc, column, wall);
				this.m_Doc.Regenerate();
			}
		}

		private UIApplication m_uiApplication;

		private Document m_Doc;
	}
}
